package com.lbssoft.gpsbd.service.impl;

import com.lbssoft.gpsbd.common.Hashing;
import com.lbssoft.gpsbd.common.Utils;
import com.lbssoft.gpsbd.dao.ConfigMapper;
import com.lbssoft.gpsbd.dao.DeviceMapper;
import com.lbssoft.gpsbd.dao.GeofenceMapper;
import com.lbssoft.gpsbd.dao.UserMapper;
import com.lbssoft.gpsbd.model.Result;
import com.lbssoft.gpsbd.model.User;
import com.lbssoft.gpsbd.model.vo.UserParam;
import com.lbssoft.gpsbd.model.vo.UserVo;
import com.lbssoft.gpsbd.service.UserService;
import org.omg.CORBA.Object;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by nczc on 2018/2/21.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    public UserMapper userMapper;

    @Autowired
    public DeviceMapper deviceMapper;

    @Autowired
    public GeofenceMapper geofenceMapper;

    @Autowired
    public ConfigMapper configMapper;


    @Override
    public Result regUser(UserParam param) {
        Result result = new Result();
        if(!configMapper.getConfig().isRegistration()){
            result.setCode(1);
            result.setMsg("StopRegistration");
            return result;
        }
        //只允许注册个人用户和企业用户角色
        if(param.getRoleIds()[0]!=1&&param.getRoleIds()[0]!=2){
            result.setCode(1);
            result.setMsg("PleaseSelectType");
            return result;
        }
        if(userMapper.getUserByAccount(param.getAccount())!=null){
            result.setCode(1);
            result.setMsg("AccountAlreadyExists");
            return result;
        }

        if(!param.getPassword().equals(param.getPassword2())){
            result.setCode(1);
            result.setMsg("PasswordIsInconsistent");
            return result;
        }
        String token = Utils.getUUID();
        User user = new User();
        user.setAccount(param.getAccount());
        Hashing.HashingResult hashingResult = Hashing.createHash(param.getPassword());
        user.setHashedPassword(hashingResult.hash);
        user.setSalt(hashingResult.salt);
        user.setEmail(param.getEmail());
        user.setPhone(param.getPhone());
        userMapper.addUser(user);
        userMapper.addUserRole(param.getRoleIds()[0],user.getId());
        userMapper.udpateToken(token, user.getId());
        Map userMap = new HashMap();
        userMap.put("uid", user.getId());
        userMap.put("account", user.getAccount());
        userMap.put("token", token);
        result.setCode(0);
        result.setData(userMap);
        return result;
    }

    @Override
    @Cacheable(value = "token", key = "'token_'.concat(#token.toString())")
    public UserVo getUserByToken(String token) {
        return userMapper.getUserByToken(token);
    }

    @Override
    public List<UserVo> getUsers(String where) {
        return userMapper.getUsers(where);
    }

    @Override
    public Result delete(long id) {
        Result result = new Result();
        Map user = userMapper.getUserById(id);
        if(user.get("account").equals("root")){
            result.setCode(1);
            result.setMsg("Default administrator can not be deleted");
            return result;
        }

        if(deviceMapper.getTree(id).size()>0){
            result.setCode(1);
            result.setMsg("此账号下有设备或分组不可删除！");
            return result;
        }

        if(geofenceMapper.getGeofences(id).size()>0){
            result.setCode(1);
            result.setMsg("此账号下有围栏不可删除！");
            return result;
        }

        if(user.get("token")!=null){
            userMapper.cleanToken(user.get("token").toString(),id);
        }
        userMapper.delete(id);
        return result;
    }

    @Override
    public void updateRole(int roleId, long userId) {
        userMapper.updateRole(roleId,userId);
    }

    @Override
    public void add(User user) {
        userMapper.addUser(user);
    }

    @Override
    public void addUserRole(int roleId, long userId) {
        userMapper.addUserRole(roleId,userId);
    }

    @Override
    public void update(UserParam user) {
        userMapper.update(user);
    }

    @Override
    public void deleteUserRole(long userId) {
        userMapper.deleteUserRole(userId);
    }

    @Override
    @CacheEvict(value = "token", key = "'token_'.concat(#token.toString())")
    public void cleanToken(String token, long id) {
        userMapper.cleanToken(null,id);
    }

    @Override
    public Map<String, Object> getUserById(long id) {
        return userMapper.getUserById(id);
    }


    @Override
    public void updateStatus(int status, long id) {
        userMapper.updateStatus(status,id);
    }
}
